/**
* Copyright (c) By zengqh.
*
* This program is just for fun or demo, in the hope that it  
* will be useful, you can redistribute it and/or modify freely.
*
* Time: 2012/07/26
* File: OGLFBOTexture2D.cpp
* Blog: http://www.cnblogs.com/zengqh/
**/

#include "OGLFrameBuffer.h"
#include "OGLFBOTexture2D.h"

OGLFBOTexture2D::OGLFBOTexture2D(const Dimension2Di& size)
: _size(size)
{
	OGLTexture2D::_width = _size._width;
	OGLTexture2D::_height = _size._height;

	createTextureEmpty();
}

OGLFBOTexture2D::~OGLFBOTexture2D()
{

}

/* we just write demo, 
 * so i dislike to handle details like the format, 
 * type ... of the texture. RGBA.
 */
void OGLFBOTexture2D::createTextureEmpty()
{
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	glGenTextures(1, &_handle);

	glBindTexture(GL_TEXTURE_2D, _handle);
	glTexImage2D(GL_TEXTURE_2D, 0, 4, _size._width, _size._height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
	glBindTexture(GL_TEXTURE_2D, 0);
}

void OGLFBOTexture2D::onAttached(FrameBuffer* fb, u32 att)
{
	OGLFrameBuffer* ogl_fb = static_cast<OGLFrameBuffer*>(fb);

	glBindFramebuffer(GL_FRAMEBUFFER, ogl_fb->getFBO());

	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + att - FrameBuffer::ATT_Color0,
		GL_TEXTURE_2D, _handle, 0);

	glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

void OGLFBOTexture2D::onDetached(FrameBuffer* fb, u32 att)
{
	OGLFrameBuffer* ogl_fb = static_cast<OGLFrameBuffer*>(fb);

	glBindFramebuffer(GL_FRAMEBUFFER, ogl_fb->getFBO());

	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + att - FrameBuffer::ATT_Color0,
		GL_TEXTURE_2D, 0, 0);

	glBindFramebuffer(GL_FRAMEBUFFER, 0);
}